//
//  HTControlFullView.swift
//  MagaCore
//
//  Created by MrMessy on 2023/6/7.
//

import SwiftUI
import AVKit
import AppLovinSDK

struct HTControlFullView: View {
  let var_margin: CGFloat = 15
  let var_progressLandsWidth: CGFloat = var_screenHeight - 60*2 - 30*2 - 12

  @Binding var var_palyer: AVPlayer
  @Binding var var_animeTitle: String
  @Binding var var_selectEP: (() -> Void)!
  @Binding var var_nextEP: (() -> Void)!
  @Binding var var_subTitleBtnClick: (() -> Void)!
  @Binding var var_fullScreen: ((UIDeviceOrientation) -> Void)!
  @Binding var var_subState: HTEnumSubtitleState!
  @Binding var var_progressRate: Double!
  @Binding var var_startTime: String
  @Binding var var_endTime: String
  @Binding var var_during: Double
  @Binding var var_fastState: HTEnumFast
  @Binding var var_isSuspend: Bool        // 是否暂停
  @Binding var var_isShowControls: Bool
  @Binding var var_isLock: Bool
  @Binding var var_pushToPremium: () -> Void
  @State var var_onRemoveAd: () -> Void = {}

  @EnvironmentObject private var var_store: HTAppStore
  @State private var var_showBannerAd = true
  @State private var var_showBannerClose = false
  @State private var var_showMRECAd = false
  @State private var var_curSubscribe: HTSubscribe?
  @State private var var_bannerDelayTask: DispatchWorkItem = DispatchWorkItem {}
  @State private var var_controlsDelayTask: DispatchWorkItem = DispatchWorkItem {}

  var body: some View {
    ZStack {

      if var_isShowControls {
        VStack(alignment: .center, spacing: 0) {
          if !var_isLock {
            // 上面
            HStack(alignment: .center, spacing: 0) {
              Button (){
                var_fullScreen(.portrait)
              } label: {
                Image("back_white").resizable().frame(width:7, height:15).padding(.leading, var_margin * 2)
              }

              Text(var_animeTitle)
                .ht_commonTextStyle(color: Color(hex: "ffffff"), fontSize: var_h2, weight: .bold)
                .padding(.leading, var_margin)
                .lineLimit(1)
              Spacer()
              HTShareButton(var_onShare:  {
                var_palyer.pause()
                var_isSuspend = true
              }, var_onDismiss: {
                var_palyer.play()
                var_isSuspend = false
              })
              HStack {
                if var_subState == .htEnumDisable {
                  Image("subtitle_disable")
                    .ht_resizeToFit()
                    .frame(width: 40, height: 22)
                    .padding(.leading, 21)
                    .padding(.trailing, var_margin * 2)
                } else {
                  Button {
                    var_subTitleBtnClick()
                  } label: {
                    if var_subState == .htEnumOpen {
                      Image("subtitle_open")
                        .ht_resizeToFit()
                        .frame(width: 40, height: 22)
                        .padding(.leading, 21)
                    } else if var_subState == .htEnumClose {
                      Image("subtitle")
                        .ht_resizeToFit()
                        .frame(width: 40, height: 22)
                        .padding(.leading, 21)
                    }
                  }.padding(.trailing, var_margin * 2)
                }
              }
            }
            .frame(maxWidth: .infinity, maxHeight: 48, alignment: .leading)
            .padding(.top, 25)
            .background(LinearGradient(gradient: Gradient(colors: [Color(white: 0, opacity: 1), Color(white: 0, opacity: 0)]), startPoint: .top, endPoint: .bottom))
          }

          Spacer()

          ZStack(alignment: .leading) {
            // 锁屏和去广告
            VStack(alignment: .leading, spacing: 0) {
              // 锁屏
              Button {
                var_isLock.toggle()
              }label: {
                Image(var_isLock ? "lock" : "unlock")
                  .frame(width: 22, height: 22)
              }
              // 去广告
              if (!var_isLock && var_curSubscribe == nil) {
                Button {
                  var_fullScreen(.portrait)
                  var_pushToPremium()
                  var_onRemoveAd()
                }label: {
                  Image("no_ad")
                    .frame(width: 22, height: 22)
                    .padding(.top, 20)
                }
              } else {
                HStack{}
                  .frame(width: 22, height: 22)
                  .padding(.top, 20)
              }
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
            .padding(.leading, var_margin * 2 + 30)

            // 中间
            if var_fastState == .htEnumNone && !var_isLock {
              HStack() {
                Button() {
                  if var_progressRate < 10 / var_during {
                    var_progressRate = 0
                  } else {
                    var_progressRate -= 10 / var_during
                  }
                  ht_seek(second: var_during * var_progressRate)
                } label: {
                  Image("back_10").resizable().frame(width: 44, height: 44).padding(.trailing, 66)
                }
                Button() {
                  ht_startOrSuspend()
                }label: {
                  ZStack{
                    Text("").frame(width: 44, height: 44).background(Color(UIColor(white: 0, alpha: 0.25))).cornerRadius(22)
                    if var_isSuspend {
                      Image("start_triangle")
                    } else {
                      Image("suspend")
                    }
                  }.frame(alignment: .center)
                }
                Button() {
                  var_progressRate += 10 / var_during
                  ht_seek(second: var_during * var_progressRate)
                } label: {
                  Image("forward_10").resizable().frame(width: 44, height: 44).padding(.leading, 66)
                }
              }
              .frame(maxWidth: .infinity, maxHeight: .infinity)
            }
          }
          .frame(maxWidth: .infinity, maxHeight: .infinity)
          .padding(.top, 25)

          Spacer()

          if !var_isLock {
            // 下面
            VStack(alignment: .leading, spacing: 0) {
              // 进度条
              HStack(alignment: .center, spacing: 0) {
                Text(var_endTime.count > 5 && var_startTime.count < 6 ? "00:" + var_startTime : var_startTime)
                  .tracking(0.1)
                  .font(.system(size: 12))
                  .foregroundColor(Color.white)
                  .frame(width: var_endTime.count > 5 ? 60 : 40)
                Spacer()
                ZStack(alignment: .leading){
                  Capsule()
                    .fill(Color(white: 1, opacity: 0.3))
                    .frame(width: var_progressLandsWidth, height: 4, alignment: .leading)
                  Capsule()
                    .fill(Color(hex: "ffffff"))
                    .frame(width: var_progressLandsWidth * var_progressRate, height: 4)
                  Text("").frame(width: 8, height: 8).background(Color(hex: "ffffff")).cornerRadius(4).offset(x: var_progressLandsWidth * var_progressRate - 4)
                    .gesture(DragGesture()
                      .onChanged({ value in
                        if (value.location.x < 0 || value.location.x > var_progressLandsWidth) {
                          return
                        }
                        var_progressRate = value.location.x / var_progressLandsWidth
                        if !var_isSuspend {
                          var_palyer.pause()
                        }
                        var_startTime = Int(var_progressRate * var_during).ht_formatTimeLine()
                      }).onEnded({ value in
                        print(value.location.x)
                        ht_seek(second: var_during * var_progressRate)
                        if !var_isSuspend {
                          var_palyer.play()
                        }
                      })
                    )
                }
                .frame(width:var_progressLandsWidth, height: 30)
                .background(Color.clear)
                .gesture(DragGesture(minimumDistance: 0, coordinateSpace: .local).onEnded({ val in
                  print(val.location.x)
                  var_progressRate = val.location.x / var_progressLandsWidth
                  ht_seek(second: var_during * var_progressRate)
                }))
                Spacer()
                Text(var_endTime)
                  .font(.system(size: 12))
                  .foregroundColor(Color.white)
                  .frame(width: var_endTime.count > 5 ? 60 : 40)
              }
              .padding(.leading, var_margin * 2)
              .padding(.trailing, var_margin * 2)
              .padding(.bottom, 10)

              // 下一页
              HStack(alignment: .center, spacing: 0) {
                Button {
                  ht_startOrSuspend()
                }label: {
                  Image(var_isSuspend ? "start_triangle" : "suspend").padding(.leading, var_margin * 2)
                }
                Button {
                  var_nextEP!()
                }label: {
                  Image("next").padding(.leading, 23)
                }
                Spacer()
                Button {
                  var_selectEP!()
                } label: {
                  Text("Episode")
                    .ht_commonTextStyle(color: Color(hex: "ffffff"), fontSize: var_h4, weight: .bold)
                    .padding(.trailing, var_margin * 2)
                }
              }
              .padding(.bottom, 10)
            }
            .frame(maxWidth: .infinity, maxHeight: 100)
            .background(LinearGradient(gradient: Gradient(colors: [Color(white: 0, opacity: 0), Color(white: 0, opacity: 1)]), startPoint: .top, endPoint: .bottom))
          }
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
      }

      // 广告banner
      if var_showBannerAd && var_curSubscribe == nil {
        HStack{
          HTBannerAd(var_didLoad: {
            var_showBannerClose = true
          })
          .frame(width: var_screenHeight * 0.5, height: (UIDevice.current.userInterfaceIdiom == .pad) ? 90 : 50)
          if (var_showBannerClose) {
            Button {
              var_showBannerAd = false
            } label: {
              Image("ad_close_white")
                .frame(width: 24, height: 24)
            }
            .frame(width: 30, height: 30)
          }
        }
        .frame(maxHeight: (UIDevice.current.userInterfaceIdiom == .pad) ? 90 : 50, alignment: .top)
        .offset(x: 0, y: -(var_screenWidth / 2) + ((UIDevice.current.userInterfaceIdiom == .pad) ? 90 : 50))
      }

      // 原生广告
      if var_showMRECAd && var_isSuspend && var_curSubscribe == nil {
        ZStack{
          HTMRECAdView(var_onDisappear: {
            var_showMRECAd = false
          }, var_onPushPremium:  {
            var_fullScreen(.portrait)
            var_showMRECAd = false
            var_pushToPremium()
          })
        }
        .zIndex(12)
      }
    }
    .frame(width: UIDevice.ht_screenWidth(), height: UIDevice.ht_screenHeight())
    .edgesIgnoringSafeArea(.all)
    .zIndex(11)
    .onChange(of: var_isShowControls, perform: { newValue in
      if (newValue) {
        var_controlsDelayTask = DispatchWorkItem {
          var_isShowControls = false
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 5, execute: var_controlsDelayTask)
      } else {
        var_controlsDelayTask.cancel()
      }
    })
    .onChange(of: var_showBannerAd, perform: { value in
      if (value) {
        var_bannerDelayTask.cancel()
      } else {
        var_bannerDelayTask = DispatchWorkItem {
          var_showBannerAd = true
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(var_store.state.var_adState.var_adConfig?.var_mbanner_secs ?? 0), execute: var_bannerDelayTask)
      }
    })
    .onChange(of: var_isSuspend, perform: { newValue in
      if (newValue) {
        var_showMRECAd = true
      } else {
        var_showMRECAd = false
      }
    })
    .onReceive(var_store.objectWillChange) { _ in
      var_curSubscribe = var_store.state.var_subscribeState.var_curSubscribe ?? nil
    }
    .onAppear{
      var_curSubscribe = var_store.state.var_subscribeState.var_curSubscribe ?? nil
      var_controlsDelayTask = DispatchWorkItem {
        var_isShowControls = false
      }
      DispatchQueue.main.asyncAfter(deadline: .now() + 5, execute: var_controlsDelayTask)

      if (var_isSuspend) {
        var_showMRECAd = true
      }
    }
    .onDisappear{
      var_isShowControls = false
      var_showBannerAd = false
    }
  }

  func ht_startOrSuspend() {
    if var_palyer.rate == 0.0 {
      var_palyer.play()
      var_isSuspend = false
    } else {
      var_palyer.pause()
      var_isSuspend = true
    }
  }

  // 精确定位
  func ht_seek(second: Float64) {
    let var_timeScale = var_palyer.currentItem?.asset.duration.timescale
    let var_time = CMTimeMakeWithSeconds(second, preferredTimescale: var_timeScale ?? 1)
    var_palyer.seek(to: var_time, toleranceBefore: CMTime.zero, toleranceAfter: CMTime.zero)
  }
}
